import aiohttp,asyncio,aiofiles,requests,time,random
from lxml import etree

links = []
async def image_down(url,sema):
    async with sema:
        async with aiohttp.ClientSession() as cs:
            async with cs.get(url) as r1:

                name = str(url).split('-')[-1]
                async with aiofiles.open(r"D:\wps\success_image\{0}".format(name),
                                         "wb") as img:
                    await img.write(await r1.content.read())
                    print(f"{name}下载完成")
                    time.sleep(random.randint(10,15)/20)
async def main():
    tasks = []
    # 控制并发数量！！！！！！
    sema = asyncio.Semaphore(3)

    for i in links:
        tasks.append(asyncio.create_task(image_down(i,sema)))

    await asyncio.wait(tasks)

if __name__ == '__main__':

    for i in range(1,5):
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                                 "AppleWebKit/537.36 (KHTML, like Gecko) "
                                 "Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0"}
        r0 = requests.get(f'https://nmixx.jype.com/Default/Gallery?PgIndex={i}&AmSeq=1',
                          headers=headers)
        r0.encoding = "utf-8"
        ht = etree.HTML(r0.text)
        for j in range(1, 21):
            links.append(ht.xpath(
                f'//*[@id="wrap"]/div[3]/div/div[2]/div[1]/div/div/a[{j}]/@href')[0])

        asyncio.run(main())
        links.clear()
